#include "glassshader.h"

GlassShader::GlassShader(QObject *parent)
    :BaseShader(parent)
{
    m_file_vert = ":/triangles.vert";
    m_file_frag = ":/triangles.frag";
}

void GlassShader::initializeGL()
{
    BaseShader::initializeGL();

    float vertices[] = {
        // positions          // normals           // texture coords
        -0.5f, -0.5f, 0.0f,  0.0f,  0.0f, -1.0f,  0.0f, 0.0f, //顺时针
         0.5f, -0.5f, 0.0f,  0.0f,  0.0f, -1.0f,  1.0f, 0.0f,
         0.5f,  0.5f, 0.0f,  0.0f,  0.0f, -1.0f,  1.0f, 1.0f,

         0.5f,  0.5f, 0.0f,  0.0f,  0.0f, -1.0f,  1.0f, 1.0f,
        -0.5f,  0.5f, 0.0f,  0.0f,  0.0f, -1.0f,  0.0f, 1.0f,
        -0.5f, -0.5f, 0.0f,  0.0f,  0.0f, -1.0f,  0.0f, 0.0f,
    };


    aPos = m_program->attributeLocation("aPos");
    aNormal = m_program->attributeLocation("aNormal");
    aTexCoords = m_program->attributeLocation("aTexCoords");

    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glVertexAttribPointer(aPos, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), BUFFER_OFFSET(0));
    glVertexAttribPointer(aNormal, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), BUFFER_OFFSET(3 * sizeof(GLfloat)));
    glVertexAttribPointer(aTexCoords, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), BUFFER_OFFSET(6 * sizeof(GLfloat)));

    glEnableVertexAttribArray(aPos);
    glEnableVertexAttribArray(aNormal);
    glEnableVertexAttribArray(aTexCoords);

    texture = new QOpenGLTexture(QImage(":/blending_transparent_window.png").mirrored());
    texture->setMinificationFilter(QOpenGLTexture::LinearMipMapLinear);
    texture->setMagnificationFilter(QOpenGLTexture::Linear);
    texture->setWrapMode(QOpenGLTexture::DirectionS, QOpenGLTexture::ClampToEdge);
    texture->setWrapMode(QOpenGLTexture::DirectionT, QOpenGLTexture::ClampToEdge);

}

void GlassShader::paintGL()
{
    m_program->bind();

    texture->bind(0);
    glBindVertexArray(vao);

    m_program->setUniformValue("projection", projection);
    m_program->setUniformValue("view", view);

    m_program->setUniformValue("model", model);

    m_program->setUniformValue("texture_diffuse", 0);

    glDrawArrays(GL_TRIANGLES, 0, 6);

    texture->release();
    m_program->release();
}
